package com.example.baseapp.controller;

import com.example.baseapp.common.ApiResponse;
import com.example.baseapp.dto.OrderDetailDTO;
import com.example.baseapp.dto.OrderListDTO;
import com.example.baseapp.entity.OrderInfo;
import com.example.baseapp.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderController {
    
    private static final Logger logger = LoggerFactory.getLogger(OrderController.class);
    
    @Autowired
    private OrderService orderService;
    
    // 创建订单
    @PostMapping("/create")
    public ApiResponse<OrderInfo> createOrder(@RequestBody Map<String, Object> params) {
        Long userId = Long.valueOf(params.get("userId").toString());
        String userName = params.get("userName") != null ? params.get("userName").toString() : null;
        String userPhone = params.get("userPhone") != null ? params.get("userPhone").toString() : null;
        String userAddress = params.get("userAddress") != null ? params.get("userAddress").toString() : null;
        String userDepartment = params.get("userDepartment") != null ? params.get("userDepartment").toString() : null;
        List<Map<String, Object>> items = (List<Map<String, Object>>) params.get("items");
        String remark = params.get("remark") != null ? params.get("remark").toString() : null;
        return ApiResponse.success(orderService.createOrder(userId, userName, userPhone, userAddress, userDepartment, items, remark));
    }
    
    // 支付订单
    @PostMapping("/pay")
    public ApiResponse<OrderInfo> payOrder(@RequestBody Map<String, Object> params) {
        String orderNo = params.get("orderNo").toString();
        String paymentMethod = params.get("paymentMethod").toString();
        return ApiResponse.success(orderService.payOrder(orderNo, paymentMethod));
    }
    
    // 取消订单
    @PostMapping("/cancel")
    public ApiResponse<OrderInfo> cancelOrder(@RequestBody Map<String, Object> params) {
        String orderNo = params.get("orderNo").toString();
        return ApiResponse.success(orderService.cancelOrder(orderNo));
    }
    
    // 获取用户订单列表
    @PostMapping("/userOrders")
    public ApiResponse<List<OrderListDTO>> getUserOrders(@RequestBody Map<String, Object> params) {
        Long userId = Long.valueOf(params.get("userId").toString());
        List<OrderInfo> orderInfos = orderService.getUserOrders(userId);
        List<OrderListDTO> orderListDTOs = orderInfos.stream()
                .map(OrderListDTO::new)
                .collect(java.util.stream.Collectors.toList());
        return ApiResponse.success(orderListDTOs);
    }
    
    // 获取订单列表（通用）
    @PostMapping("/list")
    public ApiResponse<List<OrderListDTO>> getOrderList(@RequestBody Map<String, Object> params) {
        Long userId = Long.valueOf(params.get("userId").toString());
        List<OrderInfo> orderInfos = orderService.getUserOrders(userId);
        List<OrderListDTO> orderListDTOs = orderInfos.stream()
                .map(OrderListDTO::new)
                .collect(java.util.stream.Collectors.toList());
        return ApiResponse.success(orderListDTOs);
    }
    
    // 获取订单详情 - 支持orderId和orderNo两种参数
    @PostMapping("/detail")
    public ApiResponse<OrderDetailDTO> getOrderDetail(@RequestBody Map<String, Object> params) {
        logger.info("收到订单详情请求，参数: {}", params);
        
        String orderId = null;
        String orderNo = null;
        
        // 支持前端传递的orderId参数
        if (params.containsKey("orderId")) {
            orderId = params.get("orderId").toString();
            logger.info("从orderId参数获取订单号: {}", orderId);
        }
        
        // 也支持orderNo参数（向后兼容）
        if (params.containsKey("orderNo")) {
            orderNo = params.get("orderNo").toString();
            logger.info("从orderNo参数获取订单号: {}", orderNo);
        }
        
        // 优先使用orderId，如果没有则使用orderNo
        String finalOrderNo = orderId != null ? orderId : orderNo;
        
        if (finalOrderNo == null || finalOrderNo.trim().isEmpty()) {
            logger.warn("订单号不能为空");
            return ApiResponse.error("订单号不能为空");
        }
        
        logger.info("开始查询订单详情，订单号: {}", finalOrderNo);
        
        try {
            OrderDetailDTO orderDetail = orderService.getOrderDetail(finalOrderNo);
            if (orderDetail == null) {
                logger.warn("订单不存在，订单号: {}", finalOrderNo);
                return ApiResponse.error("订单不存在");
            }
            
            logger.info("订单详情查询成功，订单号: {}", finalOrderNo);
            return ApiResponse.success(orderDetail);
        } catch (Exception e) {
            logger.error("查询订单详情时发生异常", e);
            return ApiResponse.error("查询订单详情失败: " + e.getMessage());
        }
    }
    

} 